#!/usr/bin/python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import optparse
import re
import sys

class VarImpl(object):
  """Implement the Var function used within the DEPS file."""

  def __init__(self, local_scope):
    self._local_scope = local_scope

  def Lookup(self, var_name):
    """Implements the Var syntax."""
    if var_name in self._local_scope.get('vars', {}):
      return self._local_scope['vars'][var_name]
    raise Exception('Var is not defined: %s' % var_name)

def FindProjectRevision(project_name):
  # Parse Chromium DEPS file to find out the revision of the project in use.
  deps_content = sys.stdin.read()
  local_scope = {}
  var = VarImpl(local_scope)
  global_scope = { 'Var': var.Lookup, 'deps': {} }
  exec(deps_content, global_scope, local_scope)
  project_path = local_scope['deps'][project_name]
  match = re.search('r[^@]*@(\d+)', project_path)
  if match:
    return match.group(1)
  return project_path

def main():
  parser = optparse.OptionParser(usage='%prog [options]')
  parser.add_option(
      '', '--find_project_revision',
      default=False,
      help=('FindProjectRevision'))
  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    return 1
  if options.find_project_revision:
    print FindProjectRevision(options.find_project_revision)

  return 0

if __name__ == '__main__':
  sys.exit(main())
